package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zzyl.dto.AccessTokenDto;
import com.zzyl.dto.Code2sessionResultDto;
import com.zzyl.dto.MemberLoginDTO;
import com.zzyl.dto.PhoneNumberDto;
import com.zzyl.entity.JwtConstants;
import com.zzyl.entity.Member;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtProperties;
import com.zzyl.service.MemberService;
import com.zzyl.service.WxService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.MemberVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private WxService wxService;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public MemberVo login(MemberLoginDTO dto) {
       // Code2sessionResultDto code2Session = wxService.getCode2Session("0c38kNkl2rxSAd49tinl2j0m2d18kNkK");
        // code2session获取用户的openid
        Code2sessionResultDto code2sessionDtoResult = wxService.getCode2Session(dto.getCode());
        if(code2sessionDtoResult.getErrcode() != null){
            throw new BaseException(BasicEnum.WX_LOGIN_ERROR);
        }
        String openid = code2sessionDtoResult.getOpenid();
        log.info("openid:{}", openid);
        // 根据openid查询数据库 判断是否是首次登陆
        Member member= memberMapper.selectMemberByOpenId(openid);
        // 如果用户信息不为空，说明老用户，生成token返回
        if (member!=null){
            /*HashMap<String, Object> header = new HashMap<>();
            header.put("memberId",member.getId());
            header.put("name",member.getName());
            String token = JwtUtil.createJWT("itmeima", 2, header);
            MemberVo memberVo = BeanUtil.copyProperties(member, MemberVo.class);
            memberVo.setToken(token);
            log.info("memberVo:{}", memberVo);
            return memberVo;*/
            return buildMemberVo(member);
        }
        // 如果用户信息为空，说明是新用户
        AccessTokenDto accessToken = wxService.getAccessToken();
        PhoneNumberDto phoneNumber = wxService.getPhoneNumber(accessToken.getAccess_token(), dto.getPhoneCode());
        // 添加insert一条member数据
        if (!Objects.equals(phoneNumber.getErrcode(), 0)){
            throw new BaseException(BasicEnum.WX_LOGIN_ERROR);
        }
        log.info("phone number：{}", phoneNumber.getPhone_info().getPurePhoneNumber());
        // 生成token返回
        // 添加insert一条member数据
        Member insert = new Member();
        insert.setName(dto.getNickName());
        insert.setPhone(phoneNumber.getPhone_info().getPurePhoneNumber());
        insert.setOpenId(openid);
        insert.setGender(0);
        memberMapper.insert(insert);
        // 生成token返回
        return buildMemberVo(insert);
    }

    public MemberVo buildMemberVo(Member member){
        Map<String, Object> data= new HashMap<>();
        data.put(JwtConstants.MEMBER_ID, member.getId());
        data.put(JwtConstants.MEMBER_NAME, member.getName());
        String token = JwtUtil.createJWT(jwtProperties.getBase64EncodedSecretKey(), jwtProperties.getTtl(),  data);
        MemberVo memeberVo = BeanUtil.copyProperties(member, MemberVo.class);
        memeberVo.setToken(token);
        memeberVo.setNickName(member.getName());
        return memeberVo;
    }
}
